package com.xing.algorithm.linkedlist;

public class MergeLinkedList {

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }

        final ListNode head = new ListNode(0);
        ListNode node = head;

        while(l1 != null && l2 != null) {

            if(l1.val <= l2.val) {
                node.next = l1;
                l1 = l1.next;
            }else {
                node.next = l2;
                l2 = l2.next;
            }

            node = node.next;
        }

        if (l1 != null) {
            node.next = l1;
        } else if (l2 != null) {
            node.next = l2;
        }

        return head.next;
    }

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode();
        ListNode listNode11 = new ListNode();
        ListNode listNodel2 = new ListNode();

        listNode1.val = 1;
        listNode11.val = 2;
        listNodel2.val = 4;
        listNode1.next = listNode11;
        listNode11.next = listNodel2;

        ListNode listNode2 = new ListNode();
        ListNode listNode21 = new ListNode();
        ListNode listNode22 = new ListNode();

        listNode2.val = 1;
        listNode21.val = 3;
        listNode22.val = 4;
        listNode2.next = listNode21;
        listNode21.next = listNode22;


        ListNode newHead = mergeTwoLists(listNode1, listNode2);

        StringBuilder sb = new StringBuilder();
        while(newHead != null) {
            sb.append(newHead.val).append(">");
            newHead = newHead.next;
        }

        System.out.println(sb.toString());
    }

    static class ListNode {
        public int val;
        public ListNode next;
        public ListNode(){}
        public ListNode(int val) {
            this.val = val;
        }
    }
}
